SPB Git

Repository Public

route.ts 9.1 KB 171 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : ORIX App Universe8 * File             : src/app/astra/models/v1/[...path]/route.ts9 * Module           : app10 * Repository       : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website  : https://www.orixlab.dev12 * Created          : 2026-11-2113 * Last Modified    : 2026-11-2214 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { createHash } from "node:crypto";44import { createReadStream } from "node:fs";45import { readFile, stat } from "node:fs/promises";46import path from "node:path";47import { Readable } from "node:stream";48import { clientIp } from "@/lib/security/http";49import { rateLimit } from "@/lib/security/ratelimit";5051export const dynamic = "force-dynamic";5253/**54 * ORIX Astra model library.55 *56 *   GET /astra/models/v1/catalog.json                 the catalog the app reads57 *   GET /astra/models/v1/catalog-mac.json             the catalog of ORIX Astra for the Mac (adds larger models)58 *   GET /astra/models/v1/registry.json(.sig)        the signed index of the catalogues (ORIX Astra 3.0 and later)59 *   GET /astra/models/v1/files/<model-id>/<path>      one weight / tokenizer / config file, with Range support60 *61 * The library lives outside the deployment, in ORIX_MODELS_DIR (default ~/apps-data/orix-models), laid out as62 * v1/catalog.json and v1/files/<model-id>/<path>. A file is served only when the catalog lists it for that model63 * and its size on disk equals the size in the catalog, so the route cannot be turned into a file proxy and never64 * serves a file that no longer matches what was published. The app verifies the SHA-256 of every file itself.65 */6667type CatalogFile = { path: string; size: number; sha256: string };68type CatalogModel = { id: string; redistributable?: boolean; files: CatalogFile[] };69type Catalog = { schema: number; models: CatalogModel[] };7071const root = () => path.join(process.env.ORIX_MODELS_DIR ?? path.join(process.env.HOME ?? "", "apps-data", "orix-models"), "v1");7273/** The catalogues this route publishes: the iPhone and iPad one, and the Mac one (larger models). A file is served when any of them lists it. */74const CATALOGS = ["catalog.json", "catalog-mac.json"] as const;75type Loaded = { mtimeMs: number; raw: Buffer; etag: string; files: Map<string, Map<string, CatalogFile>> };7677const g = globalThis as typeof globalThis & { __astraCatalogs?: Map<string, Loaded> };7879async function loadOne(name: string): Promise<Loaded | null> {80  const file = path.join(root(), name);81  const st = await stat(file).catch(() => null);82  if (!st?.isFile()) return null;83  const cache = (g.__astraCatalogs ??= new Map());84  const hit = cache.get(name);85  if (hit?.mtimeMs === st.mtimeMs) return hit;86  const raw = await readFile(file);87  const parsed = JSON.parse(raw.toString("utf8")) as Catalog;88  const files = new Map<string, Map<string, CatalogFile>>();89  for (const m of parsed.models ?? []) {90    if (m.redistributable === false) continue; // weights we are not cleared to re-host are never served from here91    files.set(m.id, new Map((m.files ?? []).map((f) => [f.path, f])));92  }93  const loaded = { mtimeMs: st.mtimeMs, raw, etag: `"${createHash("sha256").update(raw).digest("hex").slice(0, 32)}"`, files };94  cache.set(name, loaded);95  return loaded;96}9798/** Every published catalogue that exists and parses. One unreadable catalogue never hides the other. */99async function loadCatalogs() {100  const out = new Map<string, Loaded>();101  for (const name of CATALOGS) {102    const c = await loadOne(name).catch(() => null);103    if (c) out.set(name, c);104  }105  return out;106}107108const base = { "X-Content-Type-Options": "nosniff", "X-Robots-Tag": "noindex", "Access-Control-Allow-Origin": "*" };109const notFound = () => new Response("Not found", { status: 404, headers: { ...base, "Cache-Control": "no-store" } });110const safeSegment = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;111112async function handle(req: Request, segments: string[], head: boolean): Promise<Response> {113  try { rateLimit("astra-models", clientIp(req), 600, 60); } catch { return new Response("Too many requests", { status: 429, headers: { ...base, "Retry-After": "60" } }); }114  const catalogs = await loadCatalogs();115  if (catalogs.size === 0) return notFound();116117  // The signed registry (index of the catalogues) and its detached Ed25519 signature. They are published together by118  // the maintainer; the server only stores them and cannot produce a valid pair (the private key is not here).119  if (segments.length === 1 && (segments[0] === "registry.json" || segments[0] === "registry.json.sig")) {120    const raw = await readFile(path.join(root(), segments[0])).catch(() => null);121    if (!raw || raw.length > 1_000_000) return notFound();122    const etag = `"${createHash("sha256").update(raw).digest("hex").slice(0, 32)}"`;123    if (req.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers: { ...base, ETag: etag } });124    return new Response(head ? null : new Uint8Array(raw), {125      headers: { ...base, "Content-Type": segments[0].endsWith(".sig") ? "text/plain; charset=utf-8" : "application/json; charset=utf-8", "Content-Length": String(raw.length), ETag: etag, "Cache-Control": "public, max-age=60" },126    });127  }128129  if (segments.length === 1) {130    const catalog = catalogs.get(segments[0]);131    if (!catalog) return notFound();132    if (req.headers.get("if-none-match") === catalog.etag) return new Response(null, { status: 304, headers: { ...base, ETag: catalog.etag } });133    return new Response(head ? null : new Uint8Array(catalog.raw), {134      headers: { ...base, "Content-Type": "application/json; charset=utf-8", "Content-Length": String(catalog.raw.length), ETag: catalog.etag, "Cache-Control": "public, max-age=300" },135    });136  }137138  if (segments.length < 3 || segments[0] !== "files") return notFound();139  const [, id, ...rest] = segments;140  if (!safeSegment.test(id) || rest.some((s) => !safeSegment.test(s) || s === "." || s === "..")) return notFound();141  const wanted = rest.join("/");142  let entry: CatalogFile | undefined;143  for (const c of catalogs.values()) { entry = c.files.get(id)?.get(wanted); if (entry) break; }144  if (!entry) return notFound();145  const dir = path.join(root(), "files", id);146  const file = path.join(dir, ...rest);147  if (!file.startsWith(dir + path.sep)) return notFound();148  const st = await stat(file).catch(() => null);149  if (!st?.isFile() || st.size !== entry.size) return notFound();150151  const headers: Record<string, string> = {152    ...base, "Content-Type": "application/octet-stream", "Accept-Ranges": "bytes", ETag: `"${entry.sha256}"`,153    "Cache-Control": "public, max-age=31536000, immutable", "X-Checksum-Sha256": entry.sha256,154  };155  const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.get("range") ?? "");156  const ifRange = req.headers.get("if-range");157  if (range && (range[1] || range[2]) && (!ifRange || ifRange === headers.ETag)) {158    const start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2]));159    const end = range[1] && range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;160    if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end || start >= st.size) {161      return new Response(null, { status: 416, headers: { ...base, "Content-Range": `bytes */${st.size}` } });162    }163    const partial = { ...headers, "Content-Length": String(end - start + 1), "Content-Range": `bytes ${start}-${end}/${st.size}` };164    return new Response(head ? null : (Readable.toWeb(createReadStream(file, { start, end })) as ReadableStream), { status: 206, headers: partial });165  }166  return new Response(head ? null : (Readable.toWeb(createReadStream(file)) as ReadableStream), { headers: { ...headers, "Content-Length": String(st.size) } });167}168169export async function GET(req: Request, { params }: { params: Promise<{ path: string[] }> }) { return handle(req, (await params).path, false); }170export async function HEAD(req: Request, { params }: { params: Promise<{ path: string[] }> }) { return handle(req, (await params).path, true); }171
Files main
Menu

Theme